﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace cs499.Database
{
    public partial class Building
    {
        bool Remove(){
            return true;
        }
    }

    public static class BuildingExtension
    {
        public static Room CreateRoom(this Building building, string number, int maxenroll)
        {
            Model1Container db = new Model1Container();
            Building thisbldincontext = db.Set<Place>().OfType<Building>().FirstOrDefault(bldtofind => bldtofind.Id == building.Id && bldtofind.Code == building.Code);
            Department thisdepincontext = db.Set<Department>().FirstOrDefault(deptofind => deptofind.Id == building.Department.Id && deptofind.Name == building.Department.Name);
            if (thisbldincontext == null) return null;

            Room newRoom = db.Set<Place>().OfType<Room>().Where(roomtofind => roomtofind.Building.Id == building.Id).FirstOrDefault(roomtofind => roomtofind.Number == number);
            if (newRoom == null)
            {
                newRoom = new Room();
                newRoom.Building = thisbldincontext;
                newRoom.Department = thisdepincontext;
                newRoom.Number = number;
                newRoom.PlaceName = thisbldincontext.Code + number.ToString();
                newRoom.Capacity = maxenroll;

                db.Set<Place>().Add(newRoom);
                db.SaveChanges();
                return newRoom;
            }
            else return null;
        }

        public static Room GetRoom(this Building building, string number = "", int ID = -1)
        {
            if (number == "" && ID == -1) return null;
            Model1Container db = new Model1Container();
            Building thisbldincontext = db.Set<Place>().OfType<Building>().FirstOrDefault(bldtofind => bldtofind.Id == building.Id && bldtofind.Code == building.Code);
            if (thisbldincontext == null) return null;

            Room newRoom = db.Set<Place>().OfType<Room>().Where(roomtofind => roomtofind.Building.Id == building.Id).FirstOrDefault(roomtofind => roomtofind.Number == number || roomtofind.Id == ID);
            return newRoom;
        }

        public static bool DeleteRooms(this Building building)
        {
            
            Model1Container db = new Model1Container();
            List<Room> Rooms = db.Set<Room>().ToList().Where(bldtofind => bldtofind.BuildingID == building.Id).ToList();
            if (Rooms.Count == 0) return false;
            foreach (Room room in Rooms) room.Delete();
            try
            {
                
                return true;
            }
            catch (Exception /*ex*/) 
            {
                return false;
            }
        }



    }
}